const app = getApp()

const apiConfig = {
  loginUrl: 'api/login'
}

const http = {
  baseURL: 'https://www.666314.xyz',
  //baseURL: 'http://www.mianfen.me',
  
  request(options) {
    return new Promise((resolve, reject) => {
      const url = this.baseURL + options.url
      const header = {
        ...options.header
      }
      const loginReg = new RegExp(`^${apiConfig.loginUrl}$`)
      if (!loginReg.test(options.url)) {
        header['token'] = app.globalData.token ? `${app.globalData.token}` : ''
      }

      wx.showLoading({ title: '加载中...' })
      wx.request({
        ...options,
        url,
        header,
        success: (res) => {
          //console.log('res:', res)
          if (res.statusCode === 401) {
            const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
wx.reLaunch({ 
  url: `/pages/login/login?redirect=/${currentPage.route}`
})
            return reject(new Error('请重新登录'))
          }
          if (res.data.status !== 200) {
            //console.error('请求失败:', res.data)
            return reject(new Error(res.data.msg || '请求失败'))
          }
          //console.log('请求成功:', res.data)
          resolve(res.data)
        },
        fail: (err) => {
          wx.showToast({
            title: '网络连接失败',
            icon: 'none'
          })
          reject(err)
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  }
}

module.exports = http